#include <network.h>
using namespace engine;
#include <MMSystem.h>

#pragma comment(lib, "winmm")

const char* IP = "122.224.9.209";
uint16 PORT = 18000;

class MyClient : public NetworkClientListener
{
public:
	MyClient()
	{
		mClient = new NetworkClient();
		mClient->addListener(this);
		mClient->connect(IP, PORT);

		mTime = 0;
		mCount = 0;
		mMax = 0;
		mMin = -1;
		mPrint = 0;
	}

	~MyClient()
	{
		SAFE_DELETE(mClient);
	}

	NetworkClient* getClient()
	{
		return mClient;
	}

	virtual void onConnected()
	{
		printf("connected\n");

		//mClient->disconnect();

		mPrint = timeGetTime() - rand() % 1000;

		NetworkStream& s = mClient->beginStream();
		s.writeUInt32(timeGetTime());
		String str;
		str.resize(100);
		s.writeString(str);
		mClient->sendStream(s);
	}

	virtual void onConnectFailed()
	{
		printf("connect failed\n");
		mClient->connect(IP, PORT);
	}

	virtual void onDisconnected()
	{
		printf("disconnected\n");
		mClient->connect(IP, PORT);
	}
	
	virtual void onMessage(NetworkStream& stream)
	{
		uint32 ping = timeGetTime() - stream.readUInt32();

		if (ping > mMax)
			mMax = ping;

		if (ping < mMin)
			mMin = ping;

		//if (timeGetTime() - mPrint > 1000)
		{
			mPrint = timeGetTime();

			uint32 avg = mCount > 0 ? mTime / mCount : 0;

			printf("ping %d avg %d, min %d, max %d\n", ping, avg, mMin, mMax);
		}

		mTime += ping;
		mCount++;

		NetworkStream& s = mClient->beginStream();
		s.writeUInt32(timeGetTime());
		String str;
		str.resize(100);
		s.writeString(str);
		mClient->sendStream(s);
	}

	NetworkClient* mClient;
	uint64 mTime;
	uint64 mCount;
	uint32 mMax;
	uint32 mMin;
	uint32 mPrint;
};



int main()
{
	WSADATA wsaData;
	WSAStartup(MAKEWORD(2, 2), &wsaData);

	timeBeginPeriod(1);

	const int CLIENT_COUNT = 1;

	MyClient* c = new MyClient[CLIENT_COUNT];

	uint32 t = timeGetTime();

	while (true)
	{
		uint32 now = timeGetTime();

		if (now - t < 1)
		{
			Sleep(1);
		}
		else
		{
			t = now;

			for (int i = 0; i < CLIENT_COUNT; i++)
			{
				c[i].getClient()->handleMessages();
			}
		}
	}

	timeEndPeriod(1);
}